package org.dingfugui.triple.protocol;

import org.dingfugui.triple.context.Event;
import org.dingfugui.triple.context.producer.ExecuteHandler;
import org.dingfugui.triple.rpc.RequestMessage;
import org.dingfugui.triple.rpc.ResponseMessage;

/**
 * Created by fugui.ding on 2015/6/9.
 */
public class RequestHandler {

    private Translator messageHandler;
    private ExecuteHandler executeHandler;

    public RequestHandler(Translator messageHandler, ExecuteHandler executeHandler) {
        this.messageHandler = messageHandler;
        this.executeHandler = executeHandler;
    }

    public byte[] handleRequest(byte[] data) {
        RequestMessage request = messageHandler.decodeRequest(data);

        Event event = new Event(request.getService(), request.getMethod(), request.getTypes(), request.getParams());
        event = executeHandler.handle(event);

        Object result = event.getResult();

        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setResult(result);

        return messageHandler.encodeResponse(responseMessage);
    }
}
